/*
 *  Blazon: A user datagram protocol re-braodcasting daemon.
 *  base-io.c: Handlers for extended file descriptors and sockets
 *
 *  Copyright 2012 Blazon development team
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.

 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "std-include.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>		/* non-blocking call */

#include "tools.h"
#include "base-io.h"
#include "log.h"
#include "blazon.h"

static dlink_list fd_list;

/* function prototypes */
void fdext_close_all(void);
void fdext_close(fdext_t *);
static fdext_t * fdext_find_fd(int);
fdext_t * bind_udp_socket(const char *, uint16_t);
static bool set_nonblocking(int);

int
fd_list_size(void)
{
	return dlink_list_length(&fd_list);
}

/* Called to make a new file descriptor extension */
static fdext_t *
fdext_add(int fd)
{
	fdext_t *F = fdext_find_fd(fd);

	/* Look to see if the FD already exists. */
	if (F != NULL)
		return F;

	F = my_malloc(sizeof(fdext_t));
	F->fd = fd;
	dlink_add(F, &F->node, &fd_list);

	return F;
}

/* Side effects: Does not close the fd */
static void
fdext_destroy(fdext_t *F)
{
	if (F == NULL)
		return;

	dlink_delete(&F->node, &fd_list);
	if (F->descr)
		my_free(F->descr);
	my_free(F);
}

void
fdext_close_all(void)
{
	fdext_t *F;
	dlink_node *ptr, *next;

	DLINK_FOREACH_SAFE(ptr, next, fd_list.head)
	{
		F = ptr->data;

		close(F->fd);
		fdext_destroy(F);
	}
}

static fdext_t *
fdext_find_fd(int fd)
{
	dlink_node *ptr;

	if (fd < 0)
		return NULL;

	DLINK_FOREACH(ptr, fd_list.head)
	{
		fdext_t *F = ptr->data;
		if (F->fd == fd)
			return F;
	}
	return NULL;
}

/* Called to open a given file descriptor */
fdext_t *
fdext_open(int fd, uint8_t type, const char *note)
{
	fdext_t *F;

	F = fdext_add(fd);

	if (F->is_open == true)
	{
		if (F != NULL && F->descr != NULL)
			log_err("FD %d (%s) is already open", fd, F->descr);
		else
			log_err("FD %d is already open", fd);
		return NULL;
	}
	F->fd = fd;
	F->type = type;
	F->is_open = true;

	if (note != NULL)
		F->descr = my_strndup(note, FDE_DESCR_SIZE);

	/* make/bind the socket? */
	/* add to kqueue? */
	return F;
}


/* Called to close a given filedescriptor */
void
fdext_close(fdext_t *F)
{
	if (F == NULL)
		return;

	/* remove from kqueue? */
	if (F->is_open == false)
		log_err("Closing an fd %d that is marked as closed!", F->fd);

	/* close the socket */
	if (F->fd >= 0)
		close(F->fd);
	else
	{
		if (F->descr != NULL)
			log_err("Tried to close fd (%s) less than 0", F->descr);
		else
			log_err("Tried to close fd less than 0");
	}

	fdext_destroy(F);
}




fdext_t *
make_socket(int family, int sock_type, int proto, const char *note)
{
	fdext_t *F;
	int sockfd;

	sockfd = socket(family, sock_type, proto);
	if (sockfd < 0)
	{
		die("socket() returned error: %s", strerror(errno));
		/*return NULL;*/
	}

	F = fdext_open(sockfd, FDE_SOCKET, note);

	if (F == NULL)
	{
		log_err("fdext_open() returns NULL on FD: %d, closing FD", sockfd);
		close(sockfd);
		return NULL;
	}

	return F;
}


fdext_t *
bind_udp_socket(const char *address, uint16_t port)
{
	/*int flags;*/
	struct sockaddr_in sa;
	fdext_t *F;

	F = make_socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL);

	if (F == NULL)
		return NULL;

	set_nonblocking(F->fd);

	/*flags = 1;*/		/* 1 = on, 0 = off */
	/*setsockopt(sock, IPPROTO_IP, IP_RECVDSTADDR, &flags, sizeof(flags));*/

	memset(&sa, 0, sizeof(struct sockaddr_in));
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	if (address[0] == '*')
		sa.sin_addr.s_addr = INADDR_ANY;
	else
		sa.sin_addr.s_addr = inet_addr(address);

	if(bind(F->fd, (struct sockaddr *) &sa, sizeof(struct sockaddr_in)) < 0)
	{
		log_err("bind() for address %s, port %d", address, port);
		fdext_close(F);
		return NULL;
	}

	F->type |= FDE_BIND;

	return F;
}


int
setup_tcp_socket(const char *address, uint16_t port)
{
	int sock, flags;
	struct sockaddr_in sa;

	sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock < 0)
	{
		log_err("socket() returned error: %s", strerror(errno));
		return -1;
	}

	flags = 1;      /* 1 = on, 0 = off */
	/*setsockopt(sock, IPPROTO_IP, IP_RECVDSTADDR, &flags, sizeof(flags));*/

	memset(&sa, 0, sizeof(struct sockaddr_in));
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	if (address[0] == '*')
		sa.sin_addr.s_addr = INADDR_ANY;
	else
		sa.sin_addr.s_addr = inet_addr(address);

	if (bind(sock, (struct sockaddr *) &sa, sizeof(struct sockaddr_in)) < 0)
	{
		log_err("bind() for address %s, port %d", address, port);
		return -1;
	}

	if (listen(sock, 5) < 0)
	{
		log_err("listen() for address %s, port %d", address, port);
		return -1;
	}

	return sock;
}



bool
set_nonblocking(int fd)
{
	int flags;

	/* Set the socket to be non-blocking */
	flags = fcntl(fd, F_GETFL, 0);
	flags |= O_NONBLOCK;
	if (fcntl(fd, F_SETFL, flags) == -1)
	{
		log_err("fcntl() nonblocking returned error: %s", strerror(errno));
		return false;
	}

	return true;
}

